import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../model.dart';
import '../state.dart';

class TabbarWidget extends StatefulWidget {
  const TabbarWidget({super.key});

  @override
  State<TabbarWidget> createState() => _TabbarWidgetState();
}

class _TabbarWidgetState extends State<TabbarWidget> {
  late ScrollController _controller;

  late StateManager _state;
  StateManager get state => _state;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _scrollPosition();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  _scrollPosition() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.animateTo(
        _controller.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    _state = context.watch<StateManager>();
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      controller: _controller,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(color: Colors.blue, width: 2)),
        ),
        constraints: BoxConstraints(
          minWidth: MediaQuery.of(context).size.width,
        ),
        child: Row(
          children: [
            ..._buildTabs(state.tabs, state.activeIndex),
            IconButton(
              // 点击事件中，显示一个可输入标题的输入框
              onPressed: () {
                state.addTab();
                state.setActiveIndex(state.tabs.length - 1);
                // 添加新元素后自动滚动到最后
                _scrollPosition();
              },
              icon: const Icon(Icons.add),
            ),
          ],
        ),
      ),
    );
  }

  _buildTabs(List<TabModel> list, int index) {
    List<Widget> widgets = [];

    for (var i = 0; i < list.length; i++) {
      final textColor = i == index ? Colors.white : Colors.black87;
      final item = InkWell(
        onTap: () => state.setActiveIndex(i),
        child: Row(
          children: [
            Text(
              list[i].name,
              style: TextStyle(color: textColor),
            ),
            IconButton(
              onPressed: () => state.removeTab(i),
              icon: Icon(Icons.close, size: 16, color: textColor),
            ),
          ],
        ),
      );
      final box = Container(
        padding: const EdgeInsets.only(left: 10),
        decoration: BoxDecoration(
            color: i == index ? Colors.blue : Colors.white,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(10),
              topRight: Radius.circular(10),
            )),
        child: item,
      );

      widgets.add(box);
    }
    return widgets;
  }
}
